#!/usr/bin/env python

from time import sleep
import sys
from constants import *

__author__ = 'alex'

import socket
import threading


class ChatClientListener(object):
    def __init__(self, socket):
        self.socket = socket

    def listen(self):
        while True:
            received = sock.recv(BUFFER_SIZE)
            print received


def login(socket):

    while True:
        print "Enter nickname: ",
        name = sys.stdin.readline().strip()
        #print name

        socket.sendto(str(LOGIN_CODE) + ' ' + name, (HOST, PORT))
        received = socket.recv(BUFFER_SIZE)
        splited_recievd = received.split()

        if int(splited_recievd[0]) == LOGIN_SUCCESSFUL_CODE:
            return splited_recievd[1]
        else:
            print "this nickname is busy"





if __name__ == "__main__":
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    listener = ChatClientListener(sock)
    listener_thread = threading.Thread(target=listener.listen)
    listener_thread.daemon = True

    id = login(sock)
    #print id
    listener_thread.start()

    while True:
        #print ">> ",
        msg = sys.stdin.readline().strip()

        
        if msg == "exit":
            sock.sendto(str(LOGOUT_CODE) + ' ' + id, (HOST, PORT))
            break
        sock.sendto(str(MSG_TO_SERVER_CODE) + ' ' + id + ' ' + msg, (HOST, PORT))

